<html lang="en" xmlns:th="http://www.thymeleaf.org"
      xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity5">
<head th:replace="layout :: common_header(~{::title},~{},~{})">
    <title>商品管理</title>
</head>
<body>
<div class="easyui-layout" style="width:100%;height:100%;">
    <div id="toolbar">
        <div>
            <!--商品管理-保存商品-->
            <a sec:authorize="hasAuthority('70eaeb1b-585f-11ea-861f-7085c2d210f2')" href="javascript:void(0)"
               class="easyui-linkbutton" iconcls="fa fa-plus" onclick="addOffering()">添加</a>
            <!--商品管理-保存商品-->
            <a sec:authorize="hasAuthority('70eaeb1b-585f-11ea-861f-7085c2d210f2')" href="javascript:void(0)"
               class="easyui-linkbutton" iconcls="fa fa-pencil" onclick="editOffering()">编辑</a>
        </div>

        <div>
            <select class="easyui-combobox" id="status" name="status" style="width:120px;"
                    data-options="editable: false,panelHeight:'auto',">
                <option value="999">请选择状态</option>
                <option th:each="statu : ${status}"
                        th:value="${statu.key}"
                        th:text="${statu.value}"></option>
            </select>
            <input id="code" class="easyui-textbox" data-options="prompt:'请输入商品编号'" style="width:120px">
            <input id="name" class="easyui-textbox" data-options="prompt:'请输入商品名称'" style="width:120px">
            <a href="javascript:void(0)" onclick="reloadDatagrid()" class="easyui-linkbutton"
               data-options="iconCls:'fa fa-search'">查询</a>
            <a href="javascript:void(0)" onclick="refreshSearch()" class="easyui-linkbutton"
               data-options="iconCls:'fa fa-refresh'">刷新</a>
        </div>
    </div>
    <table id="datagrid"></table>
</div>
<th:block th:replace="layout :: scripts"/>
<script type="text/javascript">
    $.extend($.fn.validatebox.defaults.rules, {
        repeatdisplayName: {
            validator: function (value) {
                let reg = /\d$/;

                return !reg.test(value);
            },
            message: '请输入有效的姓名'
        }
    });
    $.extend($.fn.validatebox.defaults.rules, {
        repeatOfferingCode: {
            validator: function (value) {
                let reg = /^[0-9a-zA-Z]+$/;
                return reg.test(value);
            },
            message: '请输入有效的商品编号'
        }
    });

    $(function () {
        InitDataGrid();
    });

    function refreshSearch() {
        $("#code").searchbox('setValue', '');
        $("#name").searchbox('setValue', '');
        $('#status').combobox("setValue", '');
        //$("#version").combobox('setValue', '');
        reloadDatagrid();
    }

    function reloadDatagrid() {
        let status = $('#status').combobox("getValue");
        if ($('#status').combobox("getValue") === "") {
            status = "";
        }

        $("#datagrid").datagrid("load", {
            code: $("#code").searchbox("getValue"),
            name: $("#name").searchbox("getValue"),
            status: status,
            //version: $('#version').combobox("getValue")
        });
    }

    let canEdit = [[${canEdit}]];
    let canDelete = [[${canDelete}]];
    let canPublish = [[${canPublish}]];
    let canPreview = [[${canPreview}]];
    let canReadLog = [[${canReadLog}]];
    const dataGridOffering = "#datagrid";
    const loadDataUrl = '/OfferingManage/LoadOfferingList';

    function InitDataGrid() {
        let $dataGrid = $(dataGridOffering).datagrid({
            url: loadDataUrl,
            method: 'get',
            idField: 'offeringId',
            striped: true,
            fitColumns: true,
            rowNumbers: true,
            singleSelect: true,
            pagination: true,
            nowrap: false,
            fit: true,
            pageSize: 10,
            pageList: [10, 20, 50, 100],
            showFooter: false,
            toolbar: "#toolbar",
            columns: [
                [
                    {field: 'offeringCode', title: '商品编号', width: 100, align: 'left'},
                    {field: 'categoryName', title: '商品类别', width: 100, align: 'left'},
                    {field: 'offeringName', title: '商品名称', width: 100, align: 'left'},
                    {field: 'offeringPrice', title: '商品单价', width: 100, align: 'left'},
                    {field: 'recommended', title: '是否推荐', width: 60, align: 'left', formatter: FormatterUtil.BoolFormatter},
                    //{field: 'offeringVersionString', title: '商品版本', width: 120, align: 'left'},
                    {field: 'statusString', title: '商品状态', width: 60, align: 'left'},
                    {field: 'operator', title: '操作', width: 320, align: 'left',
                        formatter: function (value, row, index) {
                            let id = row.offeringId;
                            let code = row.offeringCode;
                            let status = row.status;

                            let tdContext = '';
                            if (canEdit && (status === 0 || status === 3)) { // 可编辑商品 & 草稿||审核退回
                                tdContext += '<a class="btnAudit" style="cursor:pointer" onclick="publishOffering(\'' + id + '\', null, \' 是否完成商品编辑，提交商品审核？\')" >提交审核</a>';
                                tdContext += '<a class="btnDelete" style="cursor:pointer" onclick="removeOffering(\'' + id + '\')" >删除商品</a>';
                            }
                            if (canPublish && status === 1) { // 可审核上架商品 & 提交审核
                                tdContext += '<a class="btnAudit" style="cursor:pointer" onclick="publishOffering(\'' + id + '\', true, \' 是否审核通过，上架商品？\')" >审核通过</a>';
                                tdContext += '<a class="btnDelete" style="cursor:pointer" onclick="publishOffering(\'' + id + '\', false, \' 审核不通过，是否退回？\')" >审核退回</a>';
                            }
                            if (canDelete && (status === 2 || status === 3)) { // 可删除商品 & 审核上架||审核退回
                                tdContext += '<a class="btnAudit" style="cursor:pointer" onclick="publishOffering(\'' + id + '\', null, \' 是否下架商品？\')" >下架商品</a>';
                            }
                            if (canPreview) {
                                tdContext += '<a class="btnPreview" style="cursor:pointer" onclick="previewOffering(\'id=' + id + '\')" >商品预览</a>';
                            }
                            if (canReadLog) {

                                tdContext += '<a class="btnLog" style="cursor:pointer" onclick="openOffering(\'code=' + code + '\')" >商品日志</a>';
                            }
                            return tdContext;
                        }
                    }
                ]],
            onBeforeLoad: function (param) {
            },
            onLoadSuccess: function (data) {
                $(".btnAudit").linkbutton({iconCls: 'fa fa-pencil'});
                $(".btnDelete").linkbutton({iconCls: 'fa fa-trash'});
                $(".btnPreview").linkbutton({iconCls: 'fa fa-search'});
                $(".btnLog").linkbutton({iconCls: 'fa fa-file-text-o'});

                $dataGrid.datagrid("fixRowHeight");
            },
            onLoadError: function () {
            }
        });
    }

    function addOffering() {
        let title = "新增商品";
        openForm('', title);
    }

    function editOffering() {
        let row = $(dataGridOffering).datagrid('getSelected');
        if (row) {
            let title = "编辑商品";
            openForm(row.offeringId, title);
        } else {
            $.messager.showErrorTopCenter('系统提示', "请选择需要编辑的数据", 1000);
        }
    }

    const getFormUrl = '/OfferingManage/GetOfferingForm';

    function openForm(id) {
        MainPage_PostMessage("openSubPage", getFormUrl, "id=" + id);

        return;
    }

    const removeUrl = '/OfferingManage/RemoveOffering';

    function removeOffering(OfferingId) {
        let row = $(dataGridOffering).datagrid('getSelected');
        if (row) {
            $.messager.confirm('系统提示', '删除之后将去除该商品所有角色(所有系统)且不可恢复,是否确定删除选中数据?', function (r) {
                if (r) {
                    $.easyui.loading({msg: '正在保存数据，请稍等...'});
                    $.post(removeUrl, {id: OfferingId}, function (data) {
                        if (data.success) {
                            if (data.result) {
                                $(dataGridOffering).datagrid('reload');
                                $.messager.showInfoTopCenter('系统提示', '删除数据成功。', 1000);
                            } else {
                                $.messager.showErrorTopCenter('错误消息', '删除数据失败。');
                            }
                        } else {
                            $.messager.showInfoTopCenter('系统提示', data.message);
                        }
                        $.easyui.loaded();
                    }, 'json');
                }
            });
        }
    }

    const publishUrl = '/OfferingManage/PublishOffering';

    function publishOffering(id, isAgree, title) {
        $.messager.confirm("系统提示", title,
            function (r) {
                if (r) {
                    $.ajax({
                        url: publishUrl,
                        async: true,
                        type: 'post',
                        dataType: 'json',
                        data: {id: id, isAgree: isAgree},
                        success: function (data) {
                            if (data.success) {
                                if (data.result) {
                                    $(dataGridOffering).datagrid('reload');
                                    $.messager.showInfoTopCenter('系统提示', '操作成功！', 2000);
                                } else {
                                    $.messager.showErrorTopCenter('错误消息', '操作失败！', 2000);
                                }
                            } else {
                                $(dataGridOffering).datagrid('reload');
                                $.messager.showInfoTopCenter('系统提示', data.message, 2000);
                            }
                        },
                        error: function (e) {
                            //let error = JSON.parse(e.responseText).Message;
                            $.easyui.loaded();
                            $.messager.showInfoTopCenter('系统提示', '抱歉,你不具有当前操作的权限', 2000);
                        }
                    });
                }
            });
    }

    const previewUrl = '/OfferingManage/PreviewOffering';

    function previewOffering(queryString) {
        MainPage_PostMessage("openSubPage", previewUrl, queryString);
    }

    const logUrl = "/OfferingManage/OfferingLog";

    function openOffering(queryString) {
        MainPage_PostMessage("openSubPage", logUrl, queryString);
    }

    const existOfferingNameUrl = '/OfferingManage/ExistOfferingName';

    function existOfferingName(id) {
        $.post(existOfferingNameUrl, {id: id, OfferingName: $("#OfferingName").val()}, function (data) {
                if (data === "result") {
                    $.messager.showInfoTopCenter('系统提示', '商品名【' + $("#OfferingName").val() + '】已存在,请重新输入。');
                    $("#OfferingName").val("");
                }
                if (data === "result1") {
                    $.messager.showInfoTopCenter('系统提示', '商品名【' + $("#OfferingName").val() + '】正在审批中,请重新输入。');
                    $("#OfferingName").val("");
                }
            },
            'json');
    }

</script>
</body>
</html>